package com.lelouch.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * CyclicBarrier
 *
 * @author lcy
 * @create 2018-05-29 10:09
 */
@Slf4j
public class CyclicBarrierExample1 {


    private final static int threadCount = 20;

    private final static CyclicBarrier cyclicBarrier = new CyclicBarrier(4);

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int number = i;
            Thread.sleep(1000);
            executorService.execute(() -> {
                try {

                    test(number);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }
        executorService.shutdown();

    }

    public static void test(int threadNum) throws Exception {
        log.info("ready:{}", threadNum);
        Thread.sleep(1000);
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        log.info("continue:{}", threadNum);

    }
}
